package com.handinfo.android.ui.window;

import java.io.DataInputStream;
import java.util.concurrent.CopyOnWriteArrayList;

import android.graphics.Bitmap;

import com.handinfo.android.DWGameManager;
import com.handinfo.android.core.net.GameProtocol;
import com.handinfo.android.game.Cell;
import com.handinfo.android.game.item.Item;
import com.handinfo.android.game.item.ItemConstants;
import com.handinfo.android.game.item.ItemConsume;
import com.handinfo.android.ui.IUIWindows;
import com.handinfo.android.ui.UIWindows;
import com.handinfo.android.uicontrols.DWControlsManager;
import com.handinfo.android.uicontrols.DWDragListener;
import com.handinfo.android.uicontrols.DWListener;
import com.handinfo.android.uicontrols.controls.DWBackground;
import com.handinfo.android.uicontrols.controls.DWButton;
import com.handinfo.android.uicontrols.controls.DWControl;
import com.handinfo.android.uicontrols.controls.DWFrame;
import com.handinfo.android.uicontrols.controls.DWGrid;
import com.handinfo.android.uicontrols.controls.DWGrids;
import com.handinfo.android.uicontrols.controls.DWImageBox;
import com.handinfo.android.uicontrols.controls.DWInputBox;
import com.handinfo.android.uicontrols.controls.DWListSubItem;
import com.handinfo.android.uicontrols.controls.DWListbox;
import com.handinfo.android.uicontrols.controls.DWMessageBox;
import com.handinfo.android.uicontrols.controls.DWTabControl;
import com.handinfo.android.uicontrols.controls.DWTabPage;
import com.handinfo.android.uicontrols.controls.DWTextbox;
import com.handinfo.android.uicontrols.controls.DWTitle;
import com.handinfo.android.utils.Tools;

/**
 * 
 * @author Xiaoyingying
 * 
 * 交易
 */
public class UIExchangWindow implements IUIWindows
{
	private static final byte CLEAN = 0;
	private static final byte ADD = 1;
	private static final long LOCKTIME = Integer.MAX_VALUE;

	private long other_gameID;
	private long own_gameID;
	private String str_otherName = "";
	private Bitmap img_close; //关闭窗口图标
	private Bitmap img_nameBackground; //交易用户名字背景图片
	private Bitmap img_girdBakcground;//格子背景
	private Bitmap img_lock; //交易锁图片
	private Bitmap img_lockTarget;//交易状态图片
	private Bitmap img_tabSelectImg;// 选项卡选中的图标
	private Bitmap img_tabUnSelectImg;// 先选卡未被选中的图标
	private Bitmap img_button; //按钮图片
	private Bitmap img_anxia; //按下图片
	private Bitmap img_background; //交易栏交易背景
	private Bitmap img_page_before; //选择数量箭头
	private Bitmap img_page_next; //
	private Bitmap img_money;
	private Bitmap img_title;//标题图片
	private boolean[] m_LockColumn;
	private boolean[] m_OldLockColumn;
	private boolean[] m_LockTarget;
	private boolean[] m_OldLockTarget;

	public void init()
	{
		img_close = UIWindows.createImage("/img/newui/fanhuianniu_1.gnp");
		img_nameBackground = UIWindows.createImage("/img/newui/jiaoyimingzibeijing.gnp");
		img_girdBakcground = UIWindows.createImage("/img/newui/wupinlan.gnp");
		img_lock = UIWindows.createImage("/img/newui/jiaoyisuo.gnp");
		img_tabSelectImg = UIWindows.createImage("/img/newui/biaoqianye_2.gnp");// 选项卡选中的图标
		img_tabUnSelectImg = UIWindows.createImage("/img/newui/biaoqianye_1.gnp");// 先选卡未被选中的图标
		img_button = UIWindows.createImage("/img/newui/anniu_5.gnp");
		img_anxia = UIWindows.createImage("/img/newui/anniu_5ax.gnp");
		img_background = UIWindows.createImage("/img/newui/beibaobj_1.gnp");
		img_lock = UIWindows.createImage("/img/newui/jiaoyisuo.gnp");
		img_page_before = UIWindows.createImage("/img/newui/haoyoufyan_2.gnp");
		img_page_next = UIWindows.createImage("/img/newui/haoyoufyan_1.gnp");
		img_money = UIWindows.createImage("/img/newui/jinbi_1.gnp");
		img_lockTarget = UIWindows.createImage("/img/newui/jiaoyi_1.gnp");
		img_title = UIWindows.createImage("/img/newui/jiaoyi_2.gnp");
	}

	private DWFrame m_exchang_frame;
	private DWTitle m_exchang_title;
	private DWImageBox m_exchang_close;
	private DWBackground m_exchang_leftBackground;
	private DWBackground m_exchang_rightBackground;
	private DWBackground[] m_exchang_exchangBackground = new DWBackground[2];
	private DWTextbox m_exchang_money;
	private DWButton m_exchang_lock;
	private DWButton m_exchang_unlock;
	private DWButton m_exchang_exchang;

	private void initFrame()
	{
		if (DWControlsManager.getInstance().contains(m_exchang_frame))
		{
			DWControlsManager.getInstance().removeControl(m_exchang_frame);
			m_exchang_frame = null;
		}
		m_exchang_frame = new DWFrame(DWFrame.FRAME_TYPE_FULL);
		m_exchang_frame.setClickClose(false);
		m_exchang_title = new DWTitle("交易", m_exchang_frame);
		m_exchang_title.setBackground(img_title, false);
		m_exchang_frame.addControl(m_exchang_title);

		m_exchang_close = new DWImageBox(img_close);
		m_exchang_close.setNearAnchor(m_exchang_title, Tools.RIGHT_TOP, Tools.RIGHT_TOP);
		m_exchang_close.setTouchZoomIn(UIFixWindow.TOUCHZOOM, UIFixWindow.TOUCHZOOM);
		m_exchang_close.addListener(new DWListener() {
			public void OnDoubleClick()
			{
			}

			public void OnClick()
			{
				close((byte) 0);
			}
		});
		m_exchang_frame.addControl(m_exchang_close);

		m_exchang_leftBackground = new DWBackground((m_exchang_frame.getShowWidth() - 80) / 2, m_exchang_frame
				.getShowHeight() - 55 - img_button.getHeight());
		m_exchang_leftBackground.setNearAnchor(m_exchang_frame, Tools.RIGHT_VCENTER,
				Tools.HCENTER_VCENTER, -10, -img_button.getHeight() / 4);
		m_exchang_frame.addControl(m_exchang_leftBackground);

		m_exchang_lock = new DWButton("锁定", img_button);
		m_exchang_lock.setDownImage(img_anxia);
		m_exchang_lock.setNearAnchor(m_exchang_leftBackground, Tools.LEFT_TOP, Tools.LEFT_BOTTOM, 0, 5);
		m_exchang_lock.addListener(new DWListener() {
			public void OnDoubleClick()
			{
			}

			public void OnClick()
			{
				DWGameManager.getInstance().getSendMessage().sendTranActionClockMine((byte) 1);
			}
		});
		m_exchang_frame.addControl(m_exchang_lock);

		m_exchang_unlock = new DWButton("取消", img_button);
		m_exchang_unlock.setDownImage(img_anxia);
		m_exchang_unlock.setNearAnchor(m_exchang_leftBackground, Tools.LEFT_TOP, Tools.LEFT_BOTTOM, 0, 5);
		m_exchang_unlock.addListener(new DWListener() {
			public void OnDoubleClick()
			{
			}

			public void OnClick()
			{
				DWGameManager.getInstance().getSendMessage().sendTranActionClockMine((byte) 0);
			}
		});

		m_exchang_exchang = new DWButton("交易", img_button);
		m_exchang_exchang.setDownImage(img_anxia);
		m_exchang_exchang.setFailureTime(LOCKTIME);
		m_exchang_exchang.setNearAnchor(m_exchang_leftBackground, Tools.HCENTER_TOP, Tools.HCENTER_BOTTOM, 0, 5);
		m_exchang_exchang.addListener(new DWListener() {
			public void OnDoubleClick()
			{
			}

			public void OnClick()
			{
				Tools.debugPrintln("m_LockColumn[LOCKOWN]=" + m_LockColumn[LOCKOWN] + "m_LockColumn[LOCKOTHER]="
						+ m_LockColumn[LOCKOTHER]);
				if (m_LockColumn[LOCKOWN] && m_LockColumn[LOCKOTHER])
				{
					sendOwnList(GameProtocol.CS_TRANSACTION_COMFIRM);
				}

			}
		});
		m_exchang_frame.addControl(m_exchang_exchang);

		m_exchang_rightBackground = new DWBackground((m_exchang_frame.getShowWidth() - 80) / 2, m_exchang_frame
				.getShowHeight() - 60 - 37 - 5 - img_button.getHeight());
		m_exchang_rightBackground.setNearAnchor(m_exchang_frame, Tools.LEFT_VCENTER, Tools.HCENTER_VCENTER, 10, 37 / 2);
		m_exchang_frame.addControl(m_exchang_rightBackground);

		m_exchang_exchangBackground[0] = new DWBackground(img_background, m_exchang_leftBackground.getShowWidth() - 10,
				(m_exchang_leftBackground.getShowHeight() - 50) / 2);
		m_exchang_exchangBackground[0].setNearAnchor(m_exchang_leftBackground, Tools.HCENTER_TOP, Tools.HCENTER_TOP, 0,
				20);
		m_exchang_frame.addControl(m_exchang_exchangBackground[0]);

		m_exchang_exchangBackground[1] = new DWBackground(img_background,
				m_exchang_exchangBackground[0].getShowWidth(), m_exchang_exchangBackground[0].getShowHeight());
		m_exchang_exchangBackground[1].setNearAnchor(m_exchang_leftBackground, Tools.HCENTER_BOTTOM,
				Tools.HCENTER_BOTTOM, 0, -20);
		m_exchang_frame.addControl(m_exchang_exchangBackground[1]);

		m_exchang_money = new DWTextbox("" + DWGameManager.getInstance().m_role.m_gold + "金");
		m_exchang_money.setNearAnchor(m_exchang_rightBackground, Tools.LEFT_TOP, Tools.HCENTER_BOTTOM, 20, 5);
		m_exchang_frame.addControl(m_exchang_money);

		creatLeft();
		creatBag();
	}

	private DWBackground[] m_left_nameBackground = new DWBackground[2];
	private DWTextbox[] m_left_name = new DWTextbox[2];
	private DWGrid[][] m_left_grid = new DWGrid[2][5];
	private DWInputBox[] m_left_money = new DWInputBox[2];
	private DWImageBox[] m_left_money_img = new DWImageBox[2];
	private DWGrid  selectControl;

	/**
	 * 绘制左边的界面
	 */
	private void creatLeft()
	{
		for (int i = 0; i < 2; i++)
		{
			m_left_nameBackground[i] = new DWBackground(img_nameBackground, m_exchang_exchangBackground[i]
					.getShowWidth() - 80, m_exchang_exchangBackground[i].getShowHeight()
					- (20 + 30 + img_girdBakcground.getHeight()));
			m_left_nameBackground[i]
					.setNearAnchor(m_exchang_exchangBackground[i], Tools.LEFT_TOP, Tools.LEFT_TOP, 0, 5);

			float moveX = (m_exchang_exchangBackground[i].getShowWidth() - img_girdBakcground.getWidth() * 5) / 6;

			for (int j = 0; j < 5; j++)
			{
				m_left_grid[i][j] = new DWGrid(img_girdBakcground);

				m_left_grid[i][j].setNearAnchor(m_left_nameBackground[i], Tools.LEFT_TOP, Tools.LEFT_BOTTOM,
						(int) (moveX + (moveX + img_girdBakcground.getWidth()) * j), 5);

				m_left_grid[i][j].addObject(m_npc_exchang[i][j]);
				
				final int index = j;
				
				if (i == 0)
				{
					
					m_left_grid[i][j].addDragListener(new DWDragListener() {

						public void OnDrag(DWControl control)
						{
							if (control instanceof DWGrids)
							{
								DWGrids grids = (DWGrids) control;
								Cell cell = (Cell) grids.getTouchGrid().m_data;
								

								if(cell.m_item.m_bindingState==ItemConstants.绑定状态_是||!cell.m_item.isOperate(ItemConstants.可交易))
								{
									DWGameManager.getInstance().addSystemInfo(DWGameManager.SYSTEM_INFO_TYPE_B, "该物品不可交易");
									return;
								}
								
//								if (cell.m_item.m_num > 1)
//									choiceNum(cell, index);
//								else
									addGoods(index, cell, cell.m_item.m_num);
							}
							else if (control instanceof DWGrid)
							{
								Cell cell_begin = (Cell) ((DWGrid) control).m_data;
								Cell cell_end = m_npc_exchang[0][index];
								exchangGrid(cell_begin, cell_end);
							}
						}
					});
					m_left_grid[i][j].addListener(new DWListener() {
						public void OnDoubleClick()
						{
						}

						public void OnClick()
						{
							setSelect(m_left_grid[0][index]);

							if (m_npc_exchang[0][index].m_item != null)
							{
								showItem(m_npc_exchang[0][index], CLEAN);
							}
						}
					});
				}
				else if (i == 1)
				{
					final Cell cell = m_npc_exchang[i][j];
					m_left_grid[i][j].addListener(new DWListener() {
						public void OnDoubleClick()
						{
						}

						public void OnClick()
						{
							//选中效果
							setSelect(m_left_grid[1][index]);
							 
							if (cell.m_item != null)
								UIWindows.getInstance().m_bag.showItemMessage(cell.m_item);
						}
					});
					m_left_grid[i][j].setDarg(true);
				}
				m_exchang_frame.addControl(m_left_grid[i][j]);
			}

			m_left_nameBackground[i].setNearAnchor(m_exchang_exchangBackground[i], Tools.HCENTER_TOP,
					Tools.HCENTER_TOP, 0, 5);
			m_exchang_frame.addControl(m_left_nameBackground[i]);

			String name = "";
			switch (i) {
				case LOCKOWN:
					name = DWGameManager.getInstance().m_role.m_name;
					break;
				case LOCKOTHER:
					name = str_otherName;
					break;
			}

			m_left_name[i] = new DWTextbox(name);
			m_left_name[i].setNearAnchor(m_left_nameBackground[i], Tools.HCENTER_VCENTER, Tools.HCENTER_VCENTER);
			m_exchang_frame.addControl(m_left_name[i]);

			m_left_money[i] = new DWInputBox(130, 30, m_exchang_frame);
			if (i == 0)
			{
				m_left_money[i].addListener(new DWListener() {
					public void OnDoubleClick()
					{
					}

					public void OnClick()
					{
						String text = m_left_money[0].getText();
						if (UINpcShopWindow.isNumber(text))
						{
							int money = Integer.valueOf(text);
							if (money < 0 )
							{
								DWGameManager.getInstance()
										.addSystemInfo(DWGameManager.SYSTEM_INFO_TYPE_B, "请输入正确的数据~");
								m_left_money[0].setText("0");
							}else if(money > DWGameManager.getInstance().m_role.m_gold)
							{
								DWGameManager.getInstance()
								.addSystemInfo(DWGameManager.SYSTEM_INFO_TYPE_B, "数字超过当前上限");
								m_left_money[0].setText("0");
							}
						}
						else
						{
							m_left_money[0].setText("0");
							DWGameManager.getInstance()
							.addSystemInfo(DWGameManager.SYSTEM_INFO_TYPE_B, "请输入数字~");
						}

						sendOwnList(GameProtocol.CS_TRANSACTION_OWNLIST);
					}
				});
			}
			else
				m_left_money[i].setTouch(false);

			m_left_money[i].setNearAnchor(m_exchang_exchangBackground[i], Tools.RIGHT_BOTTOM, Tools.RIGHT_BOTTOM, -40,
					-5);
			m_left_money[i].setText("0");
			m_exchang_frame.addControl(m_left_money[i]);

			m_left_money_img[i] = new DWImageBox(img_money);
			m_left_money_img[i].setNearAnchor(m_left_money[i], Tools.LEFT_VCENTER, Tools.RIGHT_VCENTER, 6, 0);
			m_exchang_frame.addControl(m_left_money_img[i]);
		}
	}

	/**
	 * 显示交易栏物品
	 * @param cell
	 */
	DWFrame item_Frame;

	private void showItem(final Cell cell, final byte type)
	{
		if (DWControlsManager.getInstance().contains(item_Frame))
			DWControlsManager.getInstance().removeControl(item_Frame);

		item_Frame = new DWFrame((DWGameManager.Screen_Width * 3) >> 3,
				DWGameManager.Screen_Height * 7 / 9);
		item_Frame.setClickClose(true);
		item_Frame.setTouchZoomIn(0, 0);

		DWBackground item_background = new DWBackground(
				item_Frame.getShowWidth(), item_Frame.getShowHeight());
		item_background.setNearAnchor(item_Frame, Tools.LEFT_TOP, Tools.LEFT_TOP);
		item_Frame.addControl(item_background);

		DWListbox item_listbox = new DWListbox(item_Frame.getShowWidth() - 40, item_Frame.getShowHeight() - 70);
		item_listbox.setShowBackgroundRect(false);
		item_listbox.setNearAnchor(item_Frame, Tools.HCENTER_TOP, Tools.HCENTER_TOP, 0, 20);
		item_Frame.addControl(item_listbox);

		DWListSubItem item_listsubitem = new DWListSubItem();
		UIWindows.getInstance().m_bag.getItemWindow(item_listsubitem, item_listbox.getShowWidth(), cell.m_item);
		item_listsubitem.refreshControl();
		item_listbox.addSubItem(item_listsubitem);

		if (cell.m_item.m_bindingState==ItemConstants.绑定状态_否&&cell.m_item.isOperate(ItemConstants.可交易)&&!m_LockColumn[LOCKOWN])
		{
			String str_button = "";
			switch (type) {
				case ADD:
					str_button = "添加";
					break;

				case CLEAN:
					str_button = "清除";
					break;
			}

			DWButton m_item_button = new DWButton(str_button, img_button);
			m_item_button.setDownImage(img_anxia);
			m_item_button.addListener(new DWListener() {
				public void OnDoubleClick()
				{
				}

				public void OnClick()
				{
					DWControlsManager.getInstance().removeControl(item_Frame);
					switch (type) {
						case ADD:
							int index = getIndex();

							if (index < 0)
							{
								DWGameManager.getInstance().addSystemInfo(DWGameManager.SYSTEM_INFO_TYPE_B,
										"交易栏已满，清空出一格交易栏后又添加");
								return;
							}

//							if (cell.m_item.m_num > 1)
//								choiceNum(cell, index);
//							else
								addGoods(index, cell, cell.m_item.m_num);
							break;

						case CLEAN:
							DWControlsManager.getInstance().removeControl(item_Frame);
							removeGoods(cell);
							sendOwnList(GameProtocol.CS_TRANSACTION_OWNLIST);
							break;
					}

				}
			});
			m_item_button.setNearAnchor(item_listbox, Tools.HCENTER_TOP, Tools.HCENTER_BOTTOM, 0, 10);
			item_Frame.addControl(m_item_button);
		}

		DWControlsManager.getInstance().addControl(item_Frame);
	}

	private int getIndex()
	{
		int index = -1;

		for (int i = 0; i < m_npc_exchang[0].length; i++)
		{
			if (m_npc_exchang[0][i].m_item == null)
			{
				index = i;
				break;
			}
		}

		return index;
	}

	private String[] m_bag_pagTitle = { "全部", "装备", "消耗", "宝石", "其他" };
	private DWTabControl m_exchang_bag;
	private DWTabPage[] m_exchang_bagPage = new DWTabPage[m_bag_pagTitle.length];

	/**
	 * 绘制右边的界面
	 */
	private void creatBag()
	{
		m_exchang_bag = new DWTabControl(img_tabUnSelectImg, img_tabSelectImg,
				m_exchang_rightBackground.getShowWidth() - 20,
				m_exchang_rightBackground.getShowHeight() + 37 - 10);
		m_exchang_bag.setNearAnchor(m_exchang_rightBackground, Tools.HCENTER_TOP, Tools.HCENTER_TOP, 0, -37);

		for (int i = 0; i < m_bag_pagTitle.length; i++) {
			m_exchang_bagPage[i] = new DWTabPage(); // 建立标签页
			m_exchang_bagPage[i].setName(m_bag_pagTitle[i]);// 设置标签页标	
			addGrids(i);
		}
		m_exchang_bag.addTabPages(m_exchang_bagPage);
		m_exchang_bag.addListener(new DWListener() {
			public void OnDoubleClick()
			{
			}

			public void OnClick()
			{
				updateBag();
			}
		});
		updateBag();

		m_exchang_frame.addControl(m_exchang_bag);
	}

	private DWGrids[] m_bag_grids = new DWGrids[m_bag_pagTitle.length];

	/**
	 * 添加格子
	 * @param num
	 */
	private void addGrids(final int num)
	{
		m_bag_grids[num] = new DWGrids(img_girdBakcground, m_npc_bag.length, 5, 4);

		int gridsX = (m_exchang_bag.getShowWidth() - img_girdBakcground.getWidth() * 5 - 20) / 5;
		int gridsY = (m_exchang_bag.getShowHeight() - img_girdBakcground.getWidth() * 4 - 10 - 37) / 4;

		m_bag_grids[num].setInterspace(gridsX, gridsY);
		m_bag_grids[num].setNearAnchor(m_exchang_bagPage[num], Tools.LEFT_TOP, Tools.LEFT_TOP, 0, 10); // 设置控件在标签页中的位置
		m_bag_grids[num].addListener(new DWListener() {
			public void OnDoubleClick()
			{
			}

			public void OnClick()
			{
				setSelect(m_bag_grids[num].getTouchGrid());
				
				if (m_bag_grids[num].getTouchGrid().m_data != null
						&& ((Cell) m_bag_grids[num].getTouchGrid().m_data).m_item != null)
				{
					showItem((Cell) m_bag_grids[num].getTouchGrid().m_data, ADD);
				}
			}
		});

		m_bag_grids[num].addDragListener(new DWDragListener() {

			public void OnDrag(DWControl control)
			{
				if (control instanceof DWGrid)
				{
					Cell cell = (Cell) ((DWGrid) control).m_data;
					removeGoods(cell);
					sendOwnList(GameProtocol.CS_TRANSACTION_OWNLIST);
				}
			}
		});
		m_exchang_bagPage[num].addControls(m_bag_grids[num]); // 把控件添加到标签页中
	}

	/**
	 * 刷新背包
	 * @param cell
	 */
	private void updateBag()
	{
		int index = m_exchang_bag.getPageIndex();
		setGrids(index, getBagDate(index));
	}

	/**
	 * 在格子中添加数据
	 * @param num
	 * @param cell
	 */
	private void setGrids(int num, Cell[] cell)
	{
		if (cell != null && cell.length > 0)
		{
			for (int i = 0; i < m_npc_bag.length; i++) {
				m_bag_grids[num].m_grids.get(i).m_data = null;
			}
			for (int i = 0; i < cell.length; i++)
			{
				m_bag_grids[num].m_grids.get(i).addObject(cell[i]);
			}
				
		}
	}

	
	/**
	 * 获取背包数据
	 * 
	 */
	private Cell[] m_npc_bag;
	private Cell[][] m_npc_exchang;

	private Cell[] getBagDate(int subType)
	{
		Cell[] cell = null;

		if (m_npc_bag != null)
		{
			if (subType == 0)
			{
				cell = m_npc_bag;
			}
			else
			{
				int num = m_npc_bag.length;
				if (num > 0) {
					CopyOnWriteArrayList<Cell> array = new CopyOnWriteArrayList<Cell>();
					for (Cell c : m_npc_bag) {
						if (c.m_item != null && c.m_item.m_type == subType) {
							array.add(c);
						}
					}
					int size = array.size();
					cell = new Cell[size];
					for (int i = 0; i < size; i++) {
						Cell m = array.get(i);
						cell[i] = m;
						Tools.debugPrintln("m.name=" + m.m_item.m_name);
					}
					array = null;
				}
			}
		}
		return cell;
	}

	String m_buy_num = "1";
	private DWFrame m_choose_frame;

	private void choiceNum(final Cell fromCell, final int index)
	{
		m_buy_num = "1";

		if (fromCell == null)
			return;

		m_choose_frame = new DWFrame(300, 150);
		m_choose_frame.setCentre();
		m_choose_frame.setClickClose(false);

		DWTitle m_choose_tit = new DWTitle("选择个数", m_choose_frame);

		final DWInputBox m_choose_num = new DWInputBox(150, 32, m_choose_frame);
		m_choose_num.setText("" + fromCell.m_item.m_num);
		m_choose_num.setNearAnchor(m_choose_frame, Tools.HCENTER_VCENTER, Tools.HCENTER_VCENTER);
		m_choose_num.addListener(new DWListener() {
			public void OnDoubleClick()
			{
			}

			public void OnClick()
			{
				if (!m_buy_num.equals(m_choose_num.getText()))
				{
					if (UINpcShopWindow.isNumber(m_choose_num.getText()))
					{
						int num = Integer.valueOf(m_choose_num.getText());

						if (num < 1)
							num = 1;
						else if (num > fromCell.m_item.m_num)
							num = fromCell.m_item.m_num;

						m_buy_num = "" + num;
						m_choose_num.setText(m_buy_num);
					}
					else
					{
						m_choose_num.setText(m_buy_num);
					}
				}
			}
		});

		DWImageBox m_choose_ima_left = new DWImageBox(img_page_before);
		m_choose_ima_left.setNearAnchor(m_choose_num, Tools.RIGHT_VCENTER, Tools.LEFT_VCENTER, -10, 0);
		m_choose_ima_left.addListener(new DWListener() {
			public void OnDoubleClick()
			{
			}

			public void OnClick()
			{
				if (!UINpcShopWindow.isNumber(m_choose_num.getText()))
					return;

				int num = Integer.valueOf(m_choose_num.getText());

				if (num > 1)
					num--;
				else
					num = fromCell.m_item.m_num;

				m_buy_num = "" + num;
				m_choose_num.setText(m_buy_num);
				m_buy_num = "" + num;
			}
		});

		DWImageBox m_choose_ima_right = new DWImageBox(img_page_next);
		m_choose_ima_right.setNearAnchor(m_choose_num, Tools.LEFT_VCENTER, Tools.RIGHT_VCENTER, 10, 0);
		m_choose_ima_right.addListener(new DWListener() {
			public void OnDoubleClick()
			{
			}

			public void OnClick()
			{
				if (!UINpcShopWindow.isNumber(m_choose_num.getText()))
					return;

				int num = Integer.valueOf(m_choose_num.getText());

				if (num < fromCell.m_item.m_num)
					num++;
				else
					num = 1;

				m_buy_num = "" + num;
				m_choose_num.setText(m_buy_num);
				m_buy_num = "" + num;
			}
		});

		DWButton m_choose_but_1 = new DWButton("确定", img_button);
		m_choose_but_1.setDownImage(img_anxia);
		m_choose_but_1.setNearAnchor(m_choose_frame, Tools.LEFT_BOTTOM, Tools.LEFT_BOTTOM,
				10, -10);
		m_choose_but_1.addListener(new DWListener() {
			public void OnDoubleClick()
			{
			}

			public void OnClick()
			{
				DWControlsManager.getInstance().removeControl(m_choose_frame);
				m_choose_frame = null;
				if (!UINpcShopWindow.isNumber(m_choose_num.getText()))
					return;

				int num = Integer.valueOf(m_choose_num.getText());

				addGoods(index, fromCell, num);
			}
		});

		DWButton m_choose_but_2 = new DWButton("返回", img_button);
		m_choose_but_2.setDownImage(img_anxia);
		m_choose_but_2.setNearAnchor(m_choose_frame, Tools.RIGHT_BOTTOM, Tools.RIGHT_BOTTOM, -10, -10);
		m_choose_but_2.addListener(new DWListener() {
			public void OnDoubleClick()
			{
			}

			public void OnClick()
			{
				DWControlsManager.getInstance().removeControl(m_choose_frame);
				m_choose_frame = null;
			}
		});

		m_choose_frame.addControl(m_choose_tit);
		m_choose_frame.addControl(m_choose_num);
		m_choose_frame.addControl(m_choose_ima_left);
		m_choose_frame.addControl(m_choose_ima_right);
		m_choose_frame.addControl(m_choose_but_1);
		m_choose_frame.addControl(m_choose_but_2);

		DWControlsManager.getInstance().addControl(m_choose_frame);
	}

	/**
	 * 设置交易对方类型
	 */
	public void setActor(long id, String name)
	{
		other_gameID = id;
		str_otherName = name;
	}

	/**
	 * 开启交易
	 */
	public void open(byte index)
	{
		DWGameManager.getInstance().getSendMessage().sendTranActionOpen(other_gameID);
	}

	/**
	 * 打开交易
	 */
	public void openExchang()
	{
		own_gameID = DWGameManager.getInstance().m_role.m_gameId;
		m_LockColumn = new boolean[2];
		m_OldLockColumn = new boolean[2];
		m_LockTarget = new boolean[2];
		m_OldLockTarget = new boolean[2];
		selectControl = null;

		initBagDate();
		initFrame();

		DWControlsManager.getInstance().removeOtherControl();
		DWControlsManager.getInstance().addControl(m_exchang_frame);
	}

	/**
	 * 初始化数据
	 */
	private void initBagDate()
	{
		Cell[] cell = DWGameManager.getInstance().m_role.m_column_bag;
		m_npc_bag = new Cell[cell.length];
		for (int i = 0; i < cell.length; i++) {
			m_npc_bag[i] = cell[i].Clone();
		}

		m_npc_exchang = new Cell[2][5];
		for (int i = 0; i < 2; i++)
		{
			for (int j = 0; j < 5; j++)
			{
				m_npc_exchang[i][j] = new Cell();
			}
		}
	}

	/**
	 * 添加物品
	 * @param index 添加物品栏位
	 * @param cell 添加的item
	 * @param num 添加数量
	 */
	private void addGoods(int index, Cell cell, int num)
	{
		if (num < 1 || cell == null)
			return;

		if (m_npc_exchang[0][index].m_item != null)
		{
			removeGoods(m_npc_exchang[0][index]);
		}

		copyCell(m_npc_exchang[0][index], cell.Clone());
		if (num < cell.m_item.m_num)
		{
			m_npc_exchang[0][index].m_item.m_num = num;
			cell.m_item.m_num -= num;
		}
		else if (num == cell.m_item.m_num)
		{
			cleanCell(cell);
		}

		sendOwnList(GameProtocol.CS_TRANSACTION_OWNLIST); //向服务器发送列表

	}

	/**
	 * 去除物品
	 * @param cell 去除的物品
	 */
	private void removeGoods(Cell cell)
	{
		if (cell == null)
			return;

		Cell endCell = m_npc_bag[cell.m_index];

		if (endCell.m_item == null)
		{
			copyCell(m_npc_bag[cell.m_index], cell);
		}
		else
			m_npc_bag[cell.m_index].m_item.m_num += cell.m_item.m_num;

		cleanCell(cell);
		updateBag();
	}

	/**
	 * 拷贝cell
	 * @param fromCell
	 * @param endCell
	 */
	private void copyCell(Cell fromCell, Cell endCell)
	{
		fromCell.m_column_type = endCell.m_column_type;
		fromCell.m_index = endCell.m_index;
		fromCell.m_item = endCell.m_item;
		fromCell.m_selected = endCell.m_selected;
	}

	private void exchangGrid(Cell cell_begin, Cell cell_end)
	{
		Cell cell = new Cell();
		copyCell(cell, cell_begin);
		copyCell(cell_begin, cell_end);
		copyCell(cell_end, cell);
		cell = null;
	}

	/**
	 * 清理cell
	 */
	private void cleanCell(Cell cell)
	{
		cell.m_column_type = 0;
		cell.m_index = 0;
		cell.m_item = null;
		cell.m_selected = false;
	}

	public void close(byte index)
	{
		if (index == 0)
		{
			final DWMessageBox msg = new DWMessageBox("提示", "你确定要取消与对方的交易？");
			msg.addListener(new DWListener() {
				public void OnDoubleClick()
				{
				}

				public void OnClick()
				{
					DWControlsManager.getInstance().removeControl(msg);
					if (msg.getResult() == DWMessageBox.SOFTKEY_OK)
					{
						DWGameManager.getInstance().getSendMessage().sendTranActionGiveUp(other_gameID);
						cleanDate();
					}
				}
			});

			DWControlsManager.getInstance().addControl(msg);
		}
		else
		{
			cleanDate();
		}

	}

	private void cleanDate()
	{
		DWControlsManager.getInstance().removeControl(m_exchang_frame);
		m_exchang_frame = null;
		m_npc_bag = null;
		m_npc_exchang = null;
		m_LockColumn = null;
		m_OldLockColumn = null;
		m_LockTarget = null;
		m_OldLockTarget = null;
		selectControl = null;
	}

	public void dispose()
	{
	}

	public void logic()
	{
	}

	/**
	 * 发送自己的物品列表
	 */
	private void sendOwnList(int sendType)
	{
		long money = 0;
		String str_money = m_left_money[0].getText();
		if (UINpcShopWindow.isNumber(str_money))
		{
			money = Long.parseLong(str_money);
		}

		CopyOnWriteArrayList<Cell> list = new CopyOnWriteArrayList<Cell>();
		for (int i = 0; i < m_npc_exchang[0].length; i++)
		{
			if (m_npc_exchang[0][i] != null && m_npc_exchang[0][i].m_item != null)
			{
				Cell cell = m_npc_exchang[0][i].Clone();
				cell.m_index = i;
				list.add(cell);
			}
		}

		switch (sendType) {
			case GameProtocol.CS_TRANSACTION_COMFIRM:
				DWGameManager.getInstance().getSendMessage().sendTranActionComFirm(own_gameID, money, list);
				break;
			case GameProtocol.CS_TRANSACTION_OWNLIST:
				DWGameManager.getInstance().getSendMessage().sendTranActionOwnList(money, list);
				break;
		}
	}

	public void recvTranActionOpen(DataInputStream dis)
	{
		try {
			byte state = dis.readByte();
			switch (state) {
				case 0:
					openExchang();
					break;
				case 2:
					DWGameManager.getInstance().addSystemInfo(DWGameManager.SYSTEM_INFO_TYPE_B, "对方拒绝与你交易");
					break;
				case 1:
				default:
					DWGameManager.getInstance().addSystemInfo(DWGameManager.SYSTEM_INFO_TYPE_B, "交易失败");
					break;
			}
		}
		catch (Exception e) {
			Tools.debug(e);
		}
	}

	private DWImageBox[] m_img_Lock = new DWImageBox[2]; //交易栏锁图标
	private DWBackground[] m_img_LockBackground=new DWBackground[2];
	private static final byte LOCKOWN = 0;
	private static final byte LOCKOTHER = 1;

	public void updataTransaction()
	{
		Tools.debugPrintln("m_LockColumn[LOCKOWN]=" + m_LockColumn[LOCKOWN] + "m_LockColumn[LOCKOTHER]="
				+ m_LockColumn[LOCKOTHER]);
		//自己锁状态
		
		for(int i=0;i<2;i++)
		{
			if(m_LockColumn[i]!=m_OldLockColumn[i]||m_LockTarget[i]!=m_OldLockTarget[i])  //如果锁定值改变时执行
			{
				if(m_LockColumn[i])
				{
					//锁定蒙板效果
					if(m_img_LockBackground[i]==null)
					{
						m_img_LockBackground[i]=new DWBackground(m_exchang_exchangBackground[i].getShowWidth(), m_exchang_exchangBackground[i].getShowHeight());
						m_img_LockBackground[i].setFill(true);
						m_img_LockBackground[i].setFillColor(0x55039AAE);
						m_img_LockBackground[i].setNearAnchor(m_exchang_exchangBackground[i], Tools.HCENTER_VCENTER, Tools.HCENTER_VCENTER);
					}
					if(!m_exchang_frame.contains(m_img_LockBackground[i]))
						m_exchang_frame.addControl(m_img_LockBackground[i]);
					
					//锁定图标
					if (m_img_Lock[i] == null)
					{
						m_img_Lock[i] = new DWImageBox(img_lock);
						m_img_Lock[i].setNearAnchor(m_exchang_exchangBackground[i], Tools.RIGHT_TOP,
								Tools.RIGHT_TOP);
					}else
						m_img_Lock[i].setImage(img_lock);
					
					if (!m_exchang_frame.contains(m_img_Lock[i]))
						m_exchang_frame.addControl(m_img_Lock[i]);
					
					
					//如果是自己
					if(i==LOCKOWN)
					{
						for (DWGrid grid : m_left_grid[LOCKOWN]) {
							grid.setDarg(true);
						}
						m_left_money[LOCKOWN].setTouch(false);

						m_exchang_frame.removeControl(m_exchang_lock);
						m_exchang_frame.addControl(m_exchang_unlock);
					}
				}
				else
				{
					if (m_img_Lock[i] != null && m_exchang_frame.contains(m_img_Lock[i]))
					{
						m_exchang_frame.removeControl(m_img_Lock[i]);
					}
					
					if(m_img_LockBackground[i]!=null&&m_exchang_frame.contains(m_img_LockBackground[i]))
						m_exchang_frame.removeControl(m_img_LockBackground[i]);
					
					if(i==LOCKOWN)
					{
						for (DWGrid grid : m_left_grid[LOCKOWN]) {
							grid.setDarg(false);
						}
						m_left_money[LOCKOWN].setTouch(true);

						m_exchang_frame.removeControl(m_exchang_unlock);
						m_exchang_frame.addControl(m_exchang_lock);
					}

				}
			}
		}
		
		
		if(m_LockColumn[LOCKOWN]!=m_OldLockColumn[LOCKOWN]||m_LockColumn[LOCKOTHER]!=m_OldLockColumn[LOCKOTHER])
		{
			if (m_LockColumn[LOCKOWN] && m_LockColumn[LOCKOTHER])
			{
				m_exchang_exchang.setFailureTime(0);
			}
			else
				m_exchang_exchang.setFailureTime(LOCKTIME);
		}
	}
	

	/**
	 * 交易后功能锁定状态变化
	 */

	private void updataTargetLock()
	{
		
		for(int i=0;i<2;i++)
		{
			if(m_LockTarget[i]!=m_OldLockTarget[i])
			{
				if (m_LockTarget[i]) //自己锁
				{
					//改变图标
					if(m_img_Lock[i]!=null&&m_exchang_frame.contains(m_img_Lock[i]))
						m_img_Lock[i].setImage(img_lockTarget);
					
					if(i==LOCKOWN)
					{
						m_exchang_unlock.setFailureTime(LOCKTIME);
						m_exchang_exchang.setFailureTime(LOCKTIME);
					}						
				}
				
				
				if(i==LOCKOWN && (!m_LockTarget[i]))
				{
					m_exchang_unlock.setFailureTime(0);
					m_exchang_exchang.setFailureTime(LOCKTIME);
				}
			}
		}
		
	}

	/**
	 * 交易栏的锁定状态
	 * @param dis
	 */
	public void recvTranActionClock(DataInputStream dis)
	{
		try {
			long gameID1 = dis.readLong();
			Tools.debugPrintln("gameID1=" + gameID1);
			byte clock1 = dis.readByte();
			Tools.debugPrintln("clock1=" + clock1);
			int index1=getIndex(gameID1);
			m_OldLockColumn[index1]=m_LockColumn[index1];
			m_LockColumn[index1] = (clock1 == 0 ? false : true);
			
			
			long gameID2 = dis.readLong();
			Tools.debugPrintln("gameID2=" + gameID2);
			byte clock2 = dis.readByte();
			int index2=getIndex(gameID2);
			m_OldLockColumn[index2]=m_LockColumn[index2];
			m_LockColumn[index2] = (clock2 == 0 ? false : true);
			Tools.debugPrintln("clock2=" + clock2);

			updataTransaction();
		}
		catch (Exception e) {
			Tools.debug(e);
		}
	}

//	/**
//	 * 对方锁定交易栏的锁定状态
//	 * @param dis
//	 */
//	public void recvTranActionClockTarget(DataInputStream dis)
//	{
//		try {
//			byte clock = dis.readByte();
//			m_LockColumn[LOCKOTHER] = clock == 0 ? false : true;
//			updataTransaction(LOCKOTHER);
//		}
//		catch (Exception e) {
//			Tools.debug(e);
//		}
//	}

	/**
	 * 对方确认交易
	 * @param dis
	 */
	public void recvTranActionTargetComFirm(DataInputStream dis)
	{
		try {
			long gameID1 = dis.readLong();
			Tools.debugPrintln("Target gameID1=" + gameID1);
			byte clock1 = dis.readByte();
			Tools.debugPrintln("Target clock1=" + clock1);
			int index1 = getIndex(gameID1);
			m_OldLockTarget[index1] = m_LockTarget[index1];
			m_LockTarget[index1] = clock1 == 0 ? false : true;
			
			
			long gameID2 = dis.readLong();
			Tools.debugPrintln("Target gameID2=" + gameID2);
			byte clock2 = dis.readByte();
			int index2 = getIndex(gameID2);
			m_OldLockTarget[index2] = m_LockTarget[index2];
			Tools.debugPrintln("Target clock2=" + clock2);
			m_LockTarget[index2] = clock2 == 0 ? false : true;

			updataTargetLock();
		}
		catch (Exception e) {
			Tools.debug(e);
		}
	}

	/**
	 * 对方交易物品
	 * @param dis
	 */
	public void recvTranActionTargetList(DataInputStream dis)
	{
		try {
			long money = dis.readLong();

			m_left_money[1].setText("" + money);
			for (int i = 0; i < m_npc_exchang[1].length; i++)
			{
				m_npc_exchang[1][i].m_index = i;
				m_npc_exchang[1][i].m_item = null;;
			}

			int size = dis.readInt();
			Tools.debugPrintln("size=" + size);
//			CopyOnWriteArrayList<Cell> list = new CopyOnWriteArrayList<Cell>();			
			for (int i = 0; i < size; i++) {
//				Cell cell = new Cell();
//				cell.m_index = dis.readInt();
//				cell.m_item = Item.recvItemFormServer(dis);
//				list.add(cell.m_index, cell);
				int index = dis.readInt();
				m_npc_exchang[1][index].m_index = index;
				m_npc_exchang[1][index].m_item = Item.recvItemFormServer(dis);
				Tools.debugPrintln("index=" + index);
				Tools.debugPrintln("itemName=" + m_npc_exchang[1][index].m_item.m_name);
			}
//			list = null;
		}
		catch (Exception e) {
			Tools.debug(e);
		}
	}

	/**
	 * 被请求交易
	 * @param dis
	 */
	public void recvTranActionTargetRequest(DataInputStream dis)
	{
		try {
			long gameID = dis.readLong();
			String name = dis.readUTF();

			setActor(gameID, name);

			final DWMessageBox msg = new DWMessageBox("提示", name + "请求与你交易，是否同意？","同意","拒绝");
			msg.addListener(new DWListener() {
				public void OnDoubleClick()
				{
				}

				public void OnClick()
				{
					byte state = 0;
					DWControlsManager.getInstance().removeControl(msg);
					if (msg.getResult() == DWMessageBox.SOFTKEY_OK)
					{
						openExchang();
						state = 1;
					}
					DWGameManager.getInstance().getSendMessage().sendTranActionComFirmRequest(other_gameID, state);

				}
			});
			DWControlsManager.getInstance().addControl(msg);
		}
		catch (Exception e) {
			Tools.debug(e);
		}
	}

	public void recvTranActionResult(DataInputStream dis)
	{
		close((byte) 1);
		try {
			byte state = dis.readByte();
			if (state == 1) {//成功
				DWGameManager.getInstance().addSystemInfo(DWGameManager.SYSTEM_INFO_TYPE_B, "交易成功！");
			}
			else {
				DWGameManager.getInstance().addSystemInfo(DWGameManager.SYSTEM_INFO_TYPE_B, "交易失败！");
			}
		}
		catch (Exception e) {
			Tools.debug(e);
		}
	}

	/**
	 * 辨别是自己的锁还是对方的锁
	 * @param gameID
	 * @return
	 */
	private byte getIndex(long gameID)
	{
		if (gameID == own_gameID)
		{
			return LOCKOWN;
		}

		if (gameID == other_gameID)
		{
			return LOCKOTHER;
		}

		return -1;
	}
	
	private void setSelect(DWGrid grid)	
	{
		if(selectControl!=null)
			selectControl.setSelect(false);
		
		selectControl=grid;
		selectControl.setSelect(true);
	}

}
